﻿using FluentFTP;
using System.Text;

namespace Windows.FileStorage.Infrastructure
{
    public class FtpSetting
    { 
        public string Host { get; set; } = "";
        public int Port { get; set; } = 21;
        public string UserName { get; set; } = "";
        public string Password { get; set; } = "";
    }

    public class FtpHelper
    {
        FtpClient _client;
        public FtpHelper(FtpSetting ftpSetting)
        {
            _client = new(ftpSetting.Host, ftpSetting.UserName, ftpSetting.Password, ftpSetting.Port)
            {
                Encoding = Encoding.UTF8
            };
            _client.Connect();
        }
        /// <summary>
        /// 上传ftp
        /// </summary>
        /// <param name="originalAddress"></param>
        /// <param name="destinationAddress"></param>
        /// <returns></returns>
        public bool UpLoadFile(string originalAddress, string destinationAddress)
        {
            if (_client.UploadFile(originalAddress, destinationAddress, FtpRemoteExists.Overwrite, true) == FtpStatus.Success)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 以流的方式 ftp
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="destinationAddress"></param>
        /// <returns></returns>
        public bool UploadStream(Stream fileStream, string destinationAddress)
        {
            if (_client.UploadStream(fileStream, destinationAddress, FtpRemoteExists.Overwrite, true) == FtpStatus.Success)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 下载ftp
        /// </summary>
        /// <param name="originalAddress"></param>
        /// <param name="destinationAddress"></param>
        /// <returns></returns>
        public bool DownloadFile(string originalAddress, string destinationAddress)
        {
            if (_client.DownloadFile(originalAddress, destinationAddress) == FtpStatus.Success)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 以流的方式下载
        /// </summary>
        /// <param name="outStream"></param>
        /// <param name="destinationAddress"></param>
        /// <returns></returns>

        public bool DownloadStream(Stream outStream, string destinationAddress)
        {
            if (_client.DownloadStream(outStream, destinationAddress) == true)
            {
                return true;
            }
            return false;
        }
        public List<string> GetFiles(string path)
        {
            return _client.GetListing(path).Select(s=>s.FullName).ToList();
        }
    }
}